package com.izhangqian.signproject.activity;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.izhangqian.pluginapk.IActivity;
import com.izhangqian.signproject.plugin.PluginApk;
import com.izhangqian.signproject.utils.PluginManager;

public class ProxyActivity extends AppCompatActivity {
    private String mClassName;
    private PluginApk mPluginApk;
    private IActivity mPlugin;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mClassName = getIntent().getStringExtra("className");
        mPluginApk = PluginManager.getInstance(this).getApk();

        launchActivity(savedInstanceState);
    }

    private void launchActivity(Bundle savedInstanceState) {
        if (mPluginApk == null) {
            return;
        }
        try {
            Class cls = mPluginApk.getClassLoader().loadClass(mClassName);
            Object object = cls.newInstance();
            if (object instanceof IActivity) {
                mPlugin = (IActivity) object;
                mPlugin.attach(this);
                mPlugin.onCreate(savedInstanceState);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Resources getResources() {
        return mPluginApk != null ? mPluginApk.getResource() : super.getResources();
    }

    @Override
    public AssetManager getAssets() {
        return mPluginApk != null ? mPluginApk.getAssetManager() : super.getAssets();
    }

    @Override
    public ClassLoader getClassLoader() {
        return mPluginApk != null ? mPluginApk.getClassLoader(): super.getClassLoader();
    }
}
